package com.msb.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/****************************************************
 * 自定义 GateWayFilter 过滤器，需要实现接口 GlobalFilter
 * GlobalFilter：表示全局过滤器
 *
 * @author lbf
 * @date 2025/7/8 15:06
 ****************************************************/
@Component
public class MyGateWayFilter implements Ordered, GlobalFilter {

    private static final Logger log = LoggerFactory.getLogger(MyGateWayFilter.class);

    /**
     * 自定义过滤器逻辑
     *
     * @param exchange  可以拿到 Request 和 Response
     * @param chain  过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String username = request.getQueryParams().getFirst("username");
        if(StringUtils.isEmpty(username)){
            log.info("**********用户名为null，非法用户，请求被拒绝！");
            //如果username为空，返回状态码为406，不可接受的请求
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 加载过滤器的优先级顺序，数字越小优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
